﻿using OrderSystem.Common;
using OrderSystem.DataAccess;
using OrderSystem.Templet;
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace OrderSystem
{
    public partial class FormDataAnalyze : FormTemplet
    {
        private DataTable _dtImportData = null;

        private string _sInvoiceCode = null;

        private FormInvoiceInfo frmInvoiceInfo = null;

        public DataGridView dgImportData;

        public DataTable ImportData
        {
            get
            {
                return this._dtImportData;
            }
        }

        public FormDataAnalyze()
        {
            this.InitializeComponent();
            this._dtImportData = new DataTable("ImportData");
            this._dtImportData.Columns.Add(new DataColumn("状态", typeof(string)));
            this._dtImportData.Columns.Add(new DataColumn("产品ID", typeof(string)));
            this._dtImportData.Columns.Add(new DataColumn("类型", typeof(string)));
            this._dtImportData.Columns.Add(new DataColumn("单位", typeof(string)));
            this._dtImportData.Columns.Add(new DataColumn("编号", typeof(string)));
            this._dtImportData.Columns.Add(new DataColumn("宽", typeof(double)));
            this._dtImportData.Columns.Add(new DataColumn("宽(短边)", typeof(string)));
            this._dtImportData.Columns.Add(new DataColumn("高", typeof(double)));
            this._dtImportData.Columns.Add(new DataColumn("高(短边)", typeof(string)));
            this._dtImportData.Columns.Add(new DataColumn("数量", typeof(int)));
            this._dtImportData.Columns.Add(new DataColumn("面积", typeof(double)));
            this._dtImportData.Columns.Add(new DataColumn("价格", typeof(double)));
            this._dtImportData.Columns.Add(new DataColumn("备注", typeof(string)));
            this._dtImportData.Columns.Add(new DataColumn("工艺", typeof(string)));
            this._dtImportData.Columns.Add(new DataColumn("客户", typeof(string)));
            this._dtImportData.Columns.Add(new DataColumn("计划ID", typeof(int)));
            this._dtImportData.Columns.Add(new DataColumn("计划", typeof(string)));
            this.dgImportData.DataSource = this._dtImportData;
        }

        public FormDataAnalyze(Hashtable ht) : this()
        {
            this.LoadData(ht);
        }

        public FormDataAnalyze(Hashtable ht, string sInvoiceCode, FormInvoiceInfo frmInvoiceInfo) : this()
        {
            this._sInvoiceCode = sInvoiceCode;
            this.frmInvoiceInfo = frmInvoiceInfo;
            this.LoadData(ht);
        }

        public void LoadData(Hashtable ht)
        {
            DataTable dataTable = null;
            InvoiceItems invoiceItems = new InvoiceItems();
            string value = "";
            IEnumerator enumerator = ht.Keys.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if (!this.ExistsProductID(enumerator.Current.ToString(), Convert.ToInt32(ht[enumerator.Current])))
                {
                    try
                    {
                        dataTable = invoiceItems.LoadOrderItemForInvoice(enumerator.Current.ToString());
                    }
                    catch (SqlException ex)
                    {
                        MessageBox.Show(ex.Message + "\r\n\r\n或者是连接数据库的通道出现故障，请检查！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        value = ex.Message;
                    }
                    catch (Exception ex2)
                    {
                        MessageBox.Show(ex2.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        value = ex2.Message;
                    }
                    if (dataTable != null)
                    {
                        if (dataTable.Rows.Count > 0)
                        {
                            DataRow dataRow = this._dtImportData.NewRow();
                            dataRow[0] = "";
                            dataRow[1] = dataTable.Rows[0][0];
                            dataRow[2] = dataTable.Rows[0][1];
                            dataRow[3] = dataTable.Rows[0][2];
                            dataRow[4] = dataTable.Rows[0][3];
                            dataRow[5] = dataTable.Rows[0][4];
                            dataRow[6] = dataTable.Rows[0][5];
                            dataRow[7] = dataTable.Rows[0][6];
                            dataRow[8] = dataTable.Rows[0][7];
                            dataRow[9] = Convert.ToInt32(ht[enumerator.Current]);
                            dataRow[10] = dataTable.Rows[0][9];
                            dataRow[11] = dataTable.Rows[0][10];
                            dataRow[12] = dataTable.Rows[0][11];
                            dataRow[13] = dataTable.Rows[0][12];
                            dataRow[14] = dataTable.Rows[0][13];
                            dataRow[15] = dataTable.Rows[0][14];
                            dataRow[16] = dataTable.Rows[0][15];
                            this._dtImportData.Rows.Add(dataRow);
                            this.dgImportData.AutoResizeColumns();
                        }
                        else
                        {
                            DataRow dataRow = this._dtImportData.NewRow();
                            dataRow[0] = "没有找到此项";
                            dataRow[1] = enumerator.Current.ToString();
                            dataRow[2] = "";
                            dataRow[3] = "";
                            dataRow[4] = "";
                            dataRow[5] = -1;
                            dataRow[6] = -1;
                            dataRow[7] = -1;
                            dataRow[8] = -1;
                            dataRow[9] = Convert.ToInt32(ht[enumerator.Current]);
                            dataRow[10] = -1;
                            dataRow[11] = -1;
                            dataRow[12] = "";
                            dataRow[13] = "";
                            dataRow[14] = "";
                            dataRow[15] = -1;
                            dataRow[16] = "";
                            this._dtImportData.Rows.Add(dataRow);
                        }
                    }
                    else
                    {
                        DataRow dataRow = this._dtImportData.NewRow();
                        dataRow[0] = value;
                        dataRow[1] = enumerator.Current.ToString();
                        dataRow[2] = "";
                        dataRow[3] = "";
                        dataRow[4] = "";
                        dataRow[5] = -1;
                        dataRow[6] = -1;
                        dataRow[7] = -1;
                        dataRow[8] = -1;
                        dataRow[9] = Convert.ToInt32(ht[enumerator.Current]);
                        dataRow[10] = -1;
                        dataRow[11] = -1;
                        dataRow[12] = "";
                        dataRow[13] = "";
                        dataRow[14] = "";
                        dataRow[15] = -1;
                        dataRow[16] = "";
                        this._dtImportData.Rows.Add(dataRow);
                    }
                }
                if (dataTable != null)
                {
                    dataTable.Dispose();
                    dataTable = null;
                }
            }
            invoiceItems.Dispose();
            this._dtImportData.AcceptChanges();
        }

        private bool ExistsProductID(string sProductID, int nQuantity)
        {
            bool result = false;
            for (int i = 0; i < this._dtImportData.Rows.Count; i++)
            {
                if (sProductID.ToUpper() == this._dtImportData.Rows[i][1].ToString().ToUpper())
                {
                    this._dtImportData.Rows[i][9] = Convert.ToInt32(this._dtImportData.Rows[i][9]) + nQuantity;
                    if (Convert.ToInt32(this._dtImportData.Rows[i][15]) > -1)
                    {
                        decimal num = Convert.ToDecimal(this._dtImportData.Rows[i][5]) * Convert.ToDecimal(this._dtImportData.Rows[i][7]) / 1000000m;
                        this._dtImportData.Rows[i][10] = Convert.ToDecimal(num.ToString("F4")) * Convert.ToInt32(this._dtImportData.Rows[i][9]);
                    }
                    result = true;
                    break;
                }
            }
            return result;
        }

        private bool NeedSort()
        {
            bool result = false;
            if (this._dtImportData != null && this._dtImportData.Rows.Count > 0)
            {
                int num = Convert.ToInt32(this._dtImportData.Rows[0][15]);
                for (int i = 0; i < this._dtImportData.Rows.Count; i++)
                {
                    if (num != Convert.ToInt32(this._dtImportData.Rows[i][15]))
                    {
                        result = true;
                        break;
                    }
                }
            }
            return result;
        }

        private void btnDataSort_Click(object sender, EventArgs e)
        {
            if (this.NeedSort())
            {
                int num = Convert.ToInt32(this._dtImportData.Rows[0][15]);
                FormDataAnalyze formDataAnalyze = new FormDataAnalyze();
                formDataAnalyze.MdiParent = base.MdiParent;
                formDataAnalyze.Show();
                int i = 0;
                while (i < this._dtImportData.Rows.Count)
                {
                    if (num == Convert.ToInt32(this._dtImportData.Rows[i][15]))
                    {
                        DataRow dataRow = formDataAnalyze.ImportData.NewRow();
                        dataRow[0] = this._dtImportData.Rows[i][0];
                        dataRow[1] = this._dtImportData.Rows[i][1];
                        dataRow[2] = this._dtImportData.Rows[i][2];
                        dataRow[3] = this._dtImportData.Rows[i][3];
                        dataRow[4] = this._dtImportData.Rows[i][4];
                        dataRow[5] = this._dtImportData.Rows[i][5];
                        dataRow[6] = this._dtImportData.Rows[i][6];
                        dataRow[7] = this._dtImportData.Rows[i][7];
                        dataRow[8] = this._dtImportData.Rows[i][8];
                        dataRow[9] = this._dtImportData.Rows[i][9];
                        dataRow[10] = this._dtImportData.Rows[i][10];
                        dataRow[11] = this._dtImportData.Rows[i][11];
                        dataRow[12] = this._dtImportData.Rows[i][12];
                        dataRow[13] = this._dtImportData.Rows[i][13];
                        dataRow[14] = this._dtImportData.Rows[i][14];
                        dataRow[15] = this._dtImportData.Rows[i][15];
                        dataRow[16] = this._dtImportData.Rows[i][16];
                        formDataAnalyze.ImportData.Rows.Add(dataRow);
                        dataRow.AcceptChanges();
                        this._dtImportData.Rows[i].Delete();
                        this._dtImportData.Rows[i].AcceptChanges();
                        i = 0;
                    }
                    else
                    {
                        i++;
                    }
                }
            }
            else
            {
                MessageBox.Show("此数据分析表不需要分类！", "提示！", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void btnCreateInvoice_Click(object sender, EventArgs e)
        {
            if (!LoginInfo.Role[PowerName.Invoice_Create])
            {
                MessageBox.Show("你没有操作这里的权限！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (!LoginInfo.Role[PowerName.InvoiceData_Create])
            {
                MessageBox.Show("你没有操作这里的权限！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (this._dtImportData == null || this._dtImportData.Rows.Count < 1)
            {
                MessageBox.Show("此数据分析表没有数据！", "提示！", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (this.NeedSort())
            {
                MessageBox.Show("此数据分析表需要分类！\r\n请先分类再生成出货单。", "提示！", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (this._dtImportData != null && this._dtImportData.Rows.Count > 0 && Convert.ToInt32(this._dtImportData.Rows[0][15]) == -1)
            {
                MessageBox.Show("此数据分析表中的数据可能是因为数据库出现问题没有找到的数据，或则在数据库中没有此数据！\r\n\r\n请检查扫描的号码是否有扫描不完整 或 人为改动数据采集器上传的数据文件。\r\n\r\n请检查数据表中的状态栏信息的相关错误提示。", "提示！", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                if (this._sInvoiceCode == null)
                {
                    Invoices invoices = new Invoices();
                    try
                    {
                        this._sInvoiceCode = invoices.InsertInvoice("", Convert.ToInt32(this._dtImportData.Rows[0][15]), "", LoginInfo.OperatorID);
                    }
                    catch (SqlException ex)
                    {
                        MessageBox.Show(ex.Message + "\r\n\r\n或者是连接数据库的通道出现故障，请检查！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                    catch (Exception ex2)
                    {
                        MessageBox.Show(ex2.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    invoices.Dispose();
                    if (this._sInvoiceCode != null)
                    {
                        MessageBox.Show("出货单创建成功！", "Success", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        this.frmInvoiceInfo = new FormInvoiceInfo(this._sInvoiceCode);
                        this.frmInvoiceInfo.MdiParent = base.MdiParent;
                        this.frmInvoiceInfo.Show();
                        this.frmInvoiceInfo.ImportData(this._dtImportData);
                    }
                }
                else if (this.frmInvoiceInfo == null || this.frmInvoiceInfo.IsDisposed)
                {
                    this.frmInvoiceInfo = new FormInvoiceInfo(this._sInvoiceCode);
                    this.frmInvoiceInfo.MdiParent = base.MdiParent;
                    this.frmInvoiceInfo.Show();
                    this.frmInvoiceInfo.ImportData(this._dtImportData);
                }
                else
                {
                    this.frmInvoiceInfo.ImportData(this._dtImportData);
                }
                if (this._dtImportData != null && this._dtImportData.Rows.Count == 0)
                {
                    base.Close();
                }
            }
        }

        private void btnAddInvoiceItem_Click(object sender, EventArgs e)
        {
            this.txtProductID.Text = this.txtProductID.Text.Replace("n", "N");
            this.txtProductID.Text = this.txtProductID.Text.Replace("O", "o");
            if (this._dtImportData.Rows.Count < 1 && this._sInvoiceCode != null)
            {
                MessageBox.Show("此数据分析表的数据已经出库，不能再手动添加数据！", "提示！", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (this.txtProductID.Text.Trim() == "")
            {
                MessageBox.Show("请填写数据！", "提示！", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (!Regex.IsMatch(this.txtProductID.Text.Trim(), "^[0-9]{6}(([N]|[n])([O]|[o])[.])[0-9]{1,8}[-][0-9]{1,8}$"))
            {
                MessageBox.Show("你输入的出库号格式不正确\r\n格式应该是：200808No.6-36(注：No.后面是1-8位数字，-后面也是1-8位数字)", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.txtProductID.Focus();
            }
            else
            {
                this.LoadData(new Hashtable
                {
                    {
                        this.txtProductID.Text.Trim(),
                        1
                    }
                });
            }
        }

        private void btnUpdateQuantity_Click(object sender, EventArgs e)
        {
            try
            {
                string text = this.dgImportData.Rows[0].Cells[0].Value.ToString();
            }
            catch (Exception)
            {
                MessageBox.Show("表格中没有数据", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            int rowIndex = this.dgImportData.CurrentCell.RowIndex;
            string text2 = InputBox.ShowBox("请输入数量...", this.dgImportData.Rows[rowIndex].Cells[9].Value.ToString());
            if (text2 != null)
            {
                if (!Regex.IsMatch(text2.Trim(), "^[0-9]{1,}$"))
                {
                    MessageBox.Show("请输入正确的数字！（注：必须是大于0的正整数）", "提示！", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else if (Convert.ToInt32(text2.Trim()) < 1)
                {
                    MessageBox.Show("请输入大于 0 的数字！", "提示！", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    for (int i = 0; i < this._dtImportData.Rows.Count; i++)
                    {
                        if (this._dtImportData.Rows[i][1].ToString() == this.dgImportData.Rows[rowIndex].Cells[1].Value.ToString())
                        {
                            this._dtImportData.Rows[i][9] = text2;
                            if (Convert.ToInt32(this._dtImportData.Rows[i][15]) > -1)
                            {
                                decimal num = Convert.ToDecimal(this._dtImportData.Rows[i][5]) * Convert.ToDecimal(this._dtImportData.Rows[i][7]) / 1000000m;
                                this._dtImportData.Rows[i][10] = Convert.ToDecimal(num.ToString("F4")) * Convert.ToInt32(this._dtImportData.Rows[i][9]);
                            }
                            this._dtImportData.AcceptChanges();
                            this.dgImportData.Rows[rowIndex].Selected = true;
                            break;
                        }
                    }
                }
            }
        }

        private void dgImportData_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                this.btnDeleteItem_Click(null, null);
            }
        }

        private void btnDeleteItem_Click(object sender, EventArgs e)
        {
            try
            {
                string text = this.dgImportData.Rows[0].Cells[0].Value.ToString();
            }
            catch (Exception)
            {
                MessageBox.Show("表格中没有数据", "错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            int rowIndex = this.dgImportData.CurrentCell.RowIndex;
            if (MessageBox.Show("真的要删除数据吗？", "提示！", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                for (int i = 0; i < this._dtImportData.Rows.Count; i++)
                {
                    if (this.dgImportData.Rows[rowIndex].Cells[1].Value.ToString() == this._dtImportData.Rows[i][1].ToString())
                    {
                        this._dtImportData.Rows[i].Delete();
                        this._dtImportData.AcceptChanges();
                        break;
                    }
                }
            }
        }

        private void txtProductID_Enter(object sender, EventArgs e)
        {
            base.AcceptButton = this.btnAddInvoiceItem;
        }

        private void txtProductID_Leave(object sender, EventArgs e)
        {
            base.AcceptButton = null;
        }

        private void FormDataAnalyze_Load(object sender, EventArgs e)
        {
            this.dgImportData.AutoResizeColumns();
        }
    }
}
